#include <stdio.h>

#include "stm32f4xx_hal.h"

#include "uart.h"

static UART_HandleTypeDef g_uart1_handle;

void usart_init(uint32_t baudrate)
{
    g_uart1_handle.Instance = USART1;                         /* USART1 */
    g_uart1_handle.Init.BaudRate = baudrate;                    /* 波特率 */
    g_uart1_handle.Init.WordLength = UART_WORDLENGTH_8B;        /* 字长为8位数据格式 */
    g_uart1_handle.Init.StopBits = UART_STOPBITS_1;             /* 一个停止位 */
    g_uart1_handle.Init.Parity = UART_PARITY_NONE;              /* 无奇偶校验位 */
    g_uart1_handle.Init.HwFlowCtl = UART_HWCONTROL_NONE;        /* 无硬件流控 */
    g_uart1_handle.Init.Mode = UART_MODE_TX_RX;                 /* 收发模式 */
    
    HAL_UART_Init(&g_uart1_handle);                             /* HAL_UART_Init()会使能UART1 */
}


/* 重定义C库函数到串口,printf */
int fputc(int ch,FILE *f)
{
    HAL_UART_Transmit(&g_uart1_handle, (uint8_t *)&ch, 1, 1000);
    return (ch);
}
 
int fgetc(FILE *f)
{
    int ch;
    HAL_UART_Receive(&g_uart1_handle, (uint8_t *)&ch, 1, 1000);
    return ch;
}
